<template>
    <div class="app-container">
        <!-- 商品介绍 -->
        <el-card class="box-card">
            <h3>商品介绍</h3>
            <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
                <el-form-item label="商品编号" prop="goodsSn">
                    <el-input v-model="goods.goodsSn" />
                </el-form-item>
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="goods.name" />
                </el-form-item>
                <el-form-item label="专柜价格" prop="counterPrice">
                    <el-input v-model="goods.counterPrice" placeholder="0.00">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="当前价格" prop="retailPrice">
                    <el-input v-model="goods.retailPrice" placeholder="0.00">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="是否新品" prop="isNew">
                    <el-radio-group v-model="goods.isNew">
                        <el-radio :label="true">新品</el-radio>
                        <el-radio :label="false">非新品</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否热卖" prop="isHot">
                    <el-radio-group v-model="goods.isHot">
                        <el-radio :label="false">普通</el-radio>
                        <el-radio :label="true">热卖</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否在售" prop="isOnSale">
                    <el-radio-group v-model="goods.isOnSale">
                        <el-radio :label="true">在售</el-radio>
                        <el-radio :label="false">未售</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="商品图片">
                    <el-upload :headers="headers" :action="uploadPath" :show-file-list="false"
                        :on-success="uploadPicUrl" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                        <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                </el-form-item>

                <el-form-item label="宣传画廊">
                    <el-upload :action="uploadPath" :headers="headers" :limit="5" :file-list="galleryFileList"
                        :on-exceed="uploadOverrun" :on-success="handleGalleryUrl" :on-remove="handleRemove" multiple
                        accept=".jpg,.jpeg,.png,.gif" list-type="picture-card">
                        <i class="el-icon-plus" />
                    </el-upload>
                </el-form-item>

                <el-form-item label="商品单位">
                    <el-input v-model="goods.unit" placeholder="件 / 个 / 盒" />
                </el-form-item>

                <el-form-item label="关键字">
                    <el-tag v-for="tag in keywords" :key="tag" closable type="primary" @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="newKeywordVisible" ref="newKeywordInput" v-model="newKeyword"
                        class="input-new-keyword" size="small" @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm" />
                    <el-button v-else class="button-new-keyword" size="small" type="primary" @click="showInput">+
                        增加</el-button>
                </el-form-item>

                <el-form-item label="所属分类">
                    <el-cascader :options="categoryList" v-model="categoryIds" expand-trigger="hover"
                        @change="handleCategoryChange" />
                </el-form-item>

                <el-form-item label="所属品牌商">
                    <el-select v-model="goods.brandId">
                        <el-option v-for="item in brandList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品简介">
                    <el-input v-model="goods.brief" />
                </el-form-item>

                <el-form-item label="商品详细介绍">
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 商品规格 -->
        <el-card class="box-card">
            <h3>商品规格</h3>
            <el-button :plain="true" type="primary" @click="handleSpecificationShow">添加</el-button>

            <el-table :data="specifications">
                <el-table-column property="specification" label="规格名" />
                <el-table-column property="value" label="规格值">
                    <template slot-scope="scope">
                        <el-tag type="primary">
                            {{ scope.row.value }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="picUrl" label="规格图片">
                    <template slot-scope="scope">
                        <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button type="danger" size="mini"
                            @click="handleSpecificationDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 设置规格弹出框 -->
            <el-dialog :visible.sync="specVisiable" title="设置规格">
                <el-form ref="specForm" :rules="rules" :model="specForm" status-icon label-position="left"
                    label-width="100px" style="width: 400px; margin-left:50px;">
                    <el-form-item label="规格名" prop="specification">
                        <el-input v-model="specForm.specification" />
                    </el-form-item>
                    <el-form-item label="规格值" prop="value">
                        <el-input v-model="specForm.value" />
                    </el-form-item>
                    <el-form-item label="规格图片" prop="picUrl">
                        <el-upload :headers="headers" :action="uploadPath" :show-file-list="false"
                            :on-success="uploadSpecPicUrl" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                            <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon" />
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="specVisiable = false">取消</el-button>
                    <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
                </div>
            </el-dialog>
        </el-card>

        <!-- 商品库存 -->
        <el-card class="box-card">
            <h3>商品库存</h3>
            <el-table :data="products">
                <el-table-column property="value" label="货品规格">
                    <template slot-scope="scope">
                        <el-tag v-for="tag in scope.row.specifications" :key="tag">
                            {{ tag }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="price" width="100" label="货品售价" />
                <el-table-column property="number" width="100" label="货品数量" />
                <el-table-column property="url" width="100" label="货品图片">
                    <template slot-scope="scope">
                        <img v-if="scope.row.url" :src="scope.row.url" width="40">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleProductShow(scope.row)">设置</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog :visible.sync="productVisiable" title="设置货品">
                <el-form ref="productForm" :model="productForm" status-icon label-position="left" label-width="100px"
                    style="width: 400px; margin-left:50px;">
                    <el-form-item label="货品规格列" prop="specifications">
                        <el-tag v-for="tag in productForm.specifications" :key="tag">
                            {{ tag }}
                        </el-tag>
                    </el-form-item>
                    <el-form-item label="货品售价" prop="price">
                        <el-input v-model="productForm.price" />
                    </el-form-item>
                    <el-form-item label="货品数量" prop="number">
                        <el-input v-model="productForm.number" />
                    </el-form-item>
                    <el-form-item label="货品图片" prop="url">
                        <el-upload :headers="headers" :action="uploadPath" :show-file-list="false"
                            :on-success="uploadProductUrl" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                            <img v-if="productForm.url" :src="productForm.url" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon" />
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="productVisiable = false">取消</el-button>
                    <el-button type="primary" @click="handleProductEdit">确定</el-button>
                </div>
            </el-dialog>
        </el-card>

        <!-- 商品参数 -->
        <el-card class="box-card">
            <h3>商品参数</h3>
            <el-button :plain="true" type="primary" @click="handleAttributeShow">添加</el-button>
            <el-table :data="attributes">
                <el-table-column property="attribute" label="商品参数名称" />
                <el-table-column property="value" label="商品参数值" />
                <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button type="danger" size="mini" @click="handleAttributeDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog :visible.sync="attributeVisiable" title="设置商品参数">
                <el-form ref="attributeForm" :model="attributeForm" status-icon label-position="left"
                    label-width="100px" style="width: 400px; margin-left:50px;">
                    <el-form-item label="商品参数名称" prop="attribute">
                        <el-input v-model="attributeForm.attribute" />
                    </el-form-item>
                    <el-form-item label="商品参数值" prop="value">
                        <el-input v-model="attributeForm.value" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="attributeVisiable = false">取消</el-button>
                    <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
                </div>
            </el-dialog>
        </el-card>




        <!-- 取消/更新商 -->
        <div class="op-container">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleEdit">更新商品</el-button>
        </div>
    </div>
</template>
<script>
import Editor from '@tinymce/tinymce-vue'
import { detailGoods, editGoods, listCatAndBrand } from "@/api/goods"
import { createStorage, uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
    name: 'GoodsEdit',
    data() {
        return {
            uploadPath,     // 图片上传的地址
            newKeywordVisible: false,   //关键字展示与否
            newKeyword: '',     //添加关键字
            keywords: [],   //关键字数组
            galleryFileList: [],    //宣传画廊数组
            categoryList: [],   //所属分类数组
            brandList: [],      //所属品牌商数组
            categoryIds: [],    //选择的品牌商
            goods: { gallery: [] }, //goods所有信息
            specVisiable: false,    //添加商品规格弹出框
            specForm: { specification: '', value: '', picUrl: '' }, //商品规格的规格名，规格值规格图片
            specifications: [{ specification: '规格', value: '标准', picUrl: '' }],
            productVisiable: false,     //商品库存弹出框
            productForm: {      //设置货品表单
                id: 0,
                specifications: [],
                price: 0.0,
                number: 0,
                url: ''
            },
            products: [         //商品库存的列表
                { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
            ],
            attributeVisiable: false,   //控制商品参数弹出框
            attributeForm: { attribute: '', value: '' },    //弹出框的数据
            attributes: [],     //商品参数列表
            rules: {
                goodsSn: [
                    { required: true, message: '商品编号不能为空', trigger: 'blur' }
                ],
                name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }]
            },
        }
    },
    computed: {
        headers() {
            return {
                'X-Mymall-Admin-Token': getToken()
            }
        }
    },
    mounted() {
        this.init()
    },
    methods: {
        init() {
            if (this.$route.query.id == null) {
                return
            }

            const goodsId = this.$route.query.id
            detailGoods(goodsId).then(response => {
                this.goods = response.data.data.goods
                this.specifications = response.data.data.specifications
                this.products = response.data.data.products
                this.attributes = response.data.data.attributes
                this.categoryIds = response.data.data.categoryIds

                this.galleryFileList = []
                for (var i = 0; i < this.goods.gallery.length; i++) {
                    this.galleryFileList.push({
                        url: this.goods.gallery[i]
                    })
                }

                const keywords = response.data.data.goods.keywords
                if (keywords !== null) {
                    this.keywords = keywords.split(',')
                }
            })

            listCatAndBrand().then(response => {
                this.categoryList = response.data.data.categoryList
                this.brandList = response.data.data.brandList
            })
        },
        // 所属分类改变
        handleCategoryChange(value) {
            // 分类的前后的值，将分类id改为分类后的值
            this.goods.categoryId = value[value.length - 1]
        },
        // 点击取消回到list页面
        handleCancel() {
            this.$router.push({ path: '/goods/list' })
        },
        // 更新商品
        handleEdit() {
            const finalGoods = {
                goods: this.goods,
                specifications: this.specifications,
                products: this.products,
                attributes: this.attributes
            }
            editGoods(finalGoods).then(response => {
                this.$notify.success({
                    title: '成功',
                    message: '创建成功'
                })
                this.$router.push({ path: '/goods/list' })
            }).catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                    confirmButtonText: '确定',
                    type: 'error'
                })
            })
        },
        //图片上传成功
        uploadPicUrl(response) {
            this.goods.picUrl = response.data.url
        },
        // 上传图片警告
        uploadOverrun: function () {
            this.$message({
                type: 'error',
                message: '上传文件个数超出限制!最多上传5张图片!'
            })
        },
        // 上传图片成功的回调
        handleGalleryUrl(response, file, fileList) {
            if (response.errno === 0) {
                this.goods.gallery.push(response.data.url)
            }
        },
        // 移除文件成功后的回调
        handleRemove(file, fileList) {
            // 这里有两种情况
            // 1.如果删除的图片是刚才上传的图片，由于没有提交，那么图片地址是file.response.data.url
            // 此时图片的地址是本机地址
            // 2.如果图片的事后台返回的已有的图片，则图片的地址是file.url
            for (var i = 0; i < this.goods.gallery.length; i++) {
                var url
                if (file.response === undefined) {
                    url = file.url
                } else {
                    url = file.response.data.url
                }

                if (this.goods.gallery[i] === url) {
                    this.goods.gallery.splice(i, 1)
                }
            }
        },
        // 关键字添加点击事件
        showInput() {
            this.newKeywordVisible = true
            this.$nextTick(_ => {
                this.$refs.newKeywordInput.$refs.input.focus()
            })
        },
        // 关键字确认或离开事件
        handleInputConfirm() {
            const newKeyword = this.newKeyword
            if (newKeyword) {
                this.keywords.push(newKeyword)
                this.goods.keywords = this.keywords.toString()
            }
            this.newKeywordVisible = false
            this.newKeyword = ''
        },
        // 商品规格添加
        handleSpecificationShow() {
            this.specForm = { specification: '', value: '', picUrl: '' }
            this.specVisiable = true
        },
        // 商品规格添加提交
        handleSpecificationAdd() {
            var index = this.specifications.length - 1
            for (var i = 0; i < this.specifications.length; i++) {
                const v = this.specifications[i]
                if (v.specification === this.specForm.specification) {
                    index = i
                }
            }
            // 在index+1的位置删除0个元素，添加this.specForm数据
            this.specifications.splice(index + 1, 0, this.specForm)
            this.specVisiable = false

            // this.specToProduct()
        },
        // 商品规格的删除
        handleSpecificationDelete() {
            const index = this.specifications.indexOf(row)
            this.specifications.splice(index, 1)
            this.specToProduct()
        },
        // 这是个啥啊啥也看不懂
        specToProduct() {
            if (this.specifications.length === 0) {
                return
            }
            // 根据specifications创建临时规格列表
            var specValues = []
            var spec = this.specifications[0].specification
            var values = []
            values.push(0)

            for (var i = 1; i < this.specifications.length; i++) {
                const aspec = this.specifications[i].specification

                if (aspec === spec) {
                    values.push(i)
                } else {
                    specValues.push(values)
                    spec = aspec
                    values = []
                    values.push(i)
                }
            }
            specValues.push(values)

            // 根据临时规格列表生产货品规格
            // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
            var productsIndex = 0
            var products = []
            var combination = []
            var n = specValues.length
            for (var s = 0; s < n; s++) {
                combination[s] = 0
            }
            var index = 0
            var isContinue = false
            do {
                var specifications = []
                for (var x = 0; x < n; x++) {
                    var z = specValues[x][combination[x]]
                    specifications.push(this.specifications[z].value)
                }
                products[productsIndex] = {
                    id: productsIndex,
                    specifications: specifications,
                    price: 0.0,
                    number: 0,
                    url: ''
                }
                productsIndex++

                index++
                combination[n - 1] = index
                for (var j = n - 1; j >= 0; j--) {
                    if (combination[j] >= specValues[j].length) {
                        combination[j] = 0
                        index = 0
                        if (j - 1 >= 0) {
                            combination[j - 1] = combination[j - 1] + 1
                        }
                    }
                }
                isContinue = false
                for (var p = 0; p < n; p++) {
                    if (combination[p] !== 0) {
                        isContinue = true
                    }
                }
            } while (isContinue)

            this.products = products
        },
        // 商品库存设置货品
        handleProductShow(row) {
            console.log(row);
            // 合并对象
            this.productForm = Object.assign({}, row)
            this.productVisiable = true
        },
        // 商品库存设置货品中上传图片
        uploadProductUrl(response) {
            this.productForm.url = response.data.url
        },
        // 商品库存设置货品中提交数据
        handleProductEdit() {
            for (var i = 0; i < this.products.length; i++) {
                const v = this.products[i]
                if (v.id === this.productForm.id) {
                    this.products.splice(i, 1, this.productForm)
                    break
                }
            }
            this.productVisiable = false
        },
        // 上传规格图片成功的回调
        uploadSpecPicUrl(response) {
            this.specForm.picUrl = response.data.url
        },
        // 商品参数添加对话框弹出
        handleAttributeShow() {
            this.attributeForm = {}
            this.attributeVisiable = true
        },
        // 商品参数添加
        handleAttributeAdd() {
            this.attributes.unshift(this.attributeForm)
            this.attributeVisiable = false
        },
        // 商品参数删除
        handleAttributeDelete(row) {
            const index = this.attributes.indexOf(row)
            this.attributes.splice(index, 1)
        }

    },
}
</script>
<style scoped>
.el-card {
    margin-bottom: 10px;
}

.el-tag+.el-tag {
    margin-left: 10px;
}

.input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

.avatar-uploader .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 145px;
    height: 145px;
    display: block;
}
</style>